﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Comp476Project
{
    class Button
    {
        public Texture2D button;
        public String label;
        public Vector2 position, origin, scale;
        public Rectangle sourceRect;
        public int frame, spriteWidth, spriteHeight;
        public SpriteFont font;
        public bool clicked, holding;

        public Button(ref Texture2D button, String label, Vector2 position, SpriteFont font)
        {
            this.button = button;
            this.label = label;
            this.position = position;
            this.scale = new Vector2(1, 1);
            frame = 0;
            spriteWidth = 46;
            spriteHeight = 20;
            this.font = font;
            clicked = false;
            holding = false;
            sourceRect = new Rectangle(0, frame * spriteHeight, spriteWidth, spriteHeight);
            origin = new Vector2(sourceRect.Width / 2, sourceRect.Height / 2);
        }

        public void Update()
        {
            MouseState mouse = Mouse.GetState();
            bool hover = mouse.X > position.X - scale.X * .5 * spriteWidth && mouse.X < position.X + scale.X * .5 * spriteWidth && mouse.Y > position.Y - scale.Y * .5 * spriteHeight && mouse.Y < position.Y + scale.Y * .5 * spriteHeight;
            if (!hover)
            {
                frame = 0;
                holding = false;
            }
            if (hover)
            {
                frame = 1;
            }
            if (hover && mouse.LeftButton == ButtonState.Pressed)
            {
                frame = 2;
                holding = true;
            }
            if (hover && holding && mouse.LeftButton == ButtonState.Released)
            {
                clicked = true;
            }
            sourceRect = new Rectangle(0, frame * spriteHeight, spriteWidth, spriteHeight);
            origin = new Vector2(sourceRect.Width / 2, sourceRect.Height / 2);
        }

        public void Reset()
        {
            holding = false;
            clicked = false;
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(button, position, sourceRect, Color.White, 0f, origin, scale, SpriteEffects.None, 0);
            //Vector2 topLeft = new Vector2((float)(-scale.X * .5 * spriteWidth), (float)(-scale.Y * .5 * spriteHeight));
            //Vector2 align = new Vector2(75 - label.Length * 7, 15);
            Vector2 topLeft = new Vector2((float)(-scale.X * .5 * spriteWidth), (float)(-scale.Y * .5 * spriteHeight));
            Vector2 align = new Vector2(21.0f - (label.Length * 8) / 2, -1.0f);
            spriteBatch.DrawString(font, label, position + topLeft + align, Color.Black);
        }
    }
}
